package vip.yyzhu.redisadmin.api.pub.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
import redis.clients.jedis.exceptions.JedisDataException;
import vip.yyzhu.redisadmin.aop.verifyKeyType.VerifyKeyType;
import vip.yyzhu.redisadmin.jopo.ResData;
import vip.yyzhu.redisadmin.jopo.ResJson;
import vip.yyzhu.redisadmin.aop.permissions.AuthUnique;
import vip.yyzhu.redisadmin.redis.RedisData;
import vip.yyzhu.redisadmin.redis.RedisList;
import vip.yyzhu.redisadmin.util.Tool;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


@RestController
@RequestMapping(value = "/api/key", produces = "application/json;charset=UTF-8")
@SuppressWarnings("all")
public class ConController {
    @Autowired
    RedisList redisList;
    @Autowired
    Tool tool;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Object getInfo(HttpServletRequest request,
                          @RequestParam(required = false, defaultValue = "127.0.0.1") String host,
                          @RequestParam(required = false, defaultValue = "6379") int port,
                          @RequestParam(required = false, defaultValue = "") String pass) {
        String unique = Tool.getUnique(request);
        System.out.println(host);
        System.out.println(port);
        System.out.println(pass);
        try {
            //连接本地的 Redis 服务
            Jedis jedis = new Jedis(host, port);
            // 如果 Redis 服务设置了密码，需要下面这行，没有就不需要

            if (pass != null && !"".equals(pass)) {
                jedis.auth(pass);
            }
            System.out.println("连接成功");
            //查看服务是否运行
            System.out.println("服务正在运行: " + jedis.ping());
            RedisData data = new RedisData();
            data.setHost(host);
            data.setPort(port);
            data.setPass(pass);
            data.setJedis(jedis);
            redisList.add(unique, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResJson(4044, "连接失败");
        }
        return new ResJson(200, "成功");
    }

    @AuthUnique
    @RequestMapping(value = "/ping", method = RequestMethod.GET)
    public Object ping(HttpServletRequest request) {
        val data = tool.getJedisData(request);
        Map map = new HashMap();
        map.put("host",data.getHost());
        map.put("port",data.getPort());
        map.put("pass",data.getPass());
        return new ResJson(200, "成功", new ResData(map));
    }
    @AuthUnique
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public Object info(HttpServletRequest request) {
        String unique = Tool.getUnique(request);
        val jedis = redisList.getJedis(unique);
        String info = jedis.info();
        return new ResJson(200, "成功", info);
    }



    @AuthUnique
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Object list(HttpServletRequest request, @RequestParam String sx) {
        String unique = Tool.getUnique(request);
        Set<String> keys = redisList.getJedis(unique).keys("*" + (sx == null ? "" : sx) + "*");
        Long aLong = redisList.getJedis(unique).dbSize();
        ResData resData = new ResData();
        Map dat = new HashMap();
        dat.put("dbsize", aLong);
        resData.setList(keys);
        resData.setMap(dat);
        return new ResJson(200, "成功", resData);
    }

    @VerifyKeyType
    @RequestMapping(value = "/getKey", method = RequestMethod.POST)
    public Object getKey(HttpServletRequest request, @RequestParam String key) {
        String unique = Tool.getUnique(request);
        val jedis = redisList.getJedis(unique);
        String key_type = jedis.type(key);
        Long key_ttl = jedis.ttl(key);
        Object con = null;
        if ("string".equals(key_type)) {
            con = jedis.get(key);
        }
        Map map = new HashMap();
        map.put("key", key);
        map.put("type", key_type);
        map.put("ttl", key_ttl);
        map.put("con", con);
        return new ResJson(200, "成功", map);
    }



    @AuthUnique
    @RequestMapping(value = "/setTtl", method = RequestMethod.POST)
    public Object setTtl(HttpServletRequest request, @RequestParam String key, @RequestParam int ttl) {
        String unique = Tool.getUnique(request);
        val jedis = redisList.getJedis(unique);
        try {
            Long expire = jedis.expire(key, ttl);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResJson(4018, "失败");
        }
        Object con = null;
        Map map = new HashMap();
        map.put("key", key);
        map.put("ttl", ttl);
        return new ResJson(200, "成功", map);
    }

    @AuthUnique
    @RequestMapping(value = "/setDb", method = RequestMethod.POST)
    public Object setDb(HttpServletRequest request, @RequestParam int db) {
        String unique = Tool.getUnique(request);
        val jedis = redisList.getJedis(unique);
        jedis.select(db);
        return new ResJson(200, "成功");
    }


    /**
     * 删除指定的key
     *
     * @param key 要删除的key
     */
    @VerifyKeyType
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Object del(HttpServletRequest request, @RequestParam String key) {
        String unique = Tool.getUnique(request);
        val jedis = redisList.getJedis(unique);
        Long del = jedis.del(key);
        Map map = new HashMap();
        map.put("key", key);
        map.put("res", del);
        return new ResJson(200, "成功", map);
    }


    /**
     * 删除指定的key
     *
     * @param key 要删除的key
     */
    @VerifyKeyType
    @RequestMapping(value = "/scan", method = RequestMethod.POST)
    public Object scan(HttpServletRequest request,
                       @RequestParam String cursor,
                       @RequestParam(defaultValue = "100") int count,
                       @RequestParam(required = false) String match) {
        String unique = Tool.getUnique(request);
        val jedis = redisList.getJedis(unique);
        ScanParams scanParams = new ScanParams();
        scanParams.count(count);//页数
        if (match != null && !match.equals("")) {
            scanParams.match(match);
        }
        ScanResult<String> scan = jedis.scan(cursor, scanParams);
        List<String> results = scan.getResult();
        String cursor1 = scan.getStringCursor();

        Map map = new HashMap();
        map.put("cursor", cursor1);
        ResData res = new ResData();
        res.setList(results);
        return new ResJson(200, "成功", map);
    }
}
